﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.IO;
using System.Data;
using System.Data.SqlClient;


using System.Text;



namespace StreetSmartAdmin
{
    public partial class CI_Admin : System.Web.UI.Page
    {
        protected string connectstring = System.Configuration.ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"].ConnectionString;
        public static String date = DateTime.Now.Date.ToString("yyyy-MM-dd");
        public static String time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
        Userinfo user;
        protected void Page_Load(object sender, EventArgs e)
        {
            //((Label)Header.FindControl("lblUser")).Text = (String)Session["UserName"];
            //((Label)Header.FindControl("lblUser")).Text = ((Userinfo)Session["UserInfo"]).fullname; 
            //((Label)Header.FindControl("lblUser")).Text = (User.Identity.Name);
            ADODotNetCRUD crud = new ADODotNetCRUD();
            user = crud.GetUser(User.Identity.Name);
            ((Label)Header.FindControl("lblUser")).Text = (user.fullname);
            //((Label)Header.FindControl("lblGroup")).Text = (user.groupname);
            GridView1.PageSize = Convert.ToInt32(ddlpage.SelectedValue);            
            //GridView1.AllowPaging = false;
            //GridView1.DataBind();
            //gridViewTotalRowCount.Text = Convert.ToString(GridView1.Rows.Count);
            //GridView1.AllowPaging = true;
            //GridView1.DataBind();
            if (MultiView1.ActiveViewIndex == 0 && MultiView2.ActiveViewIndex == 0)
            {
                btnUpdate.Visible = false;
            }
            else {
                btnUpdate.Visible = true;
            }

            //((DropDownList)DetailsView2.FindControl("SelELEC_PRICE_TYPE")).Items.Insert(0, new ListItem("",""));

            

        }

        protected void Sel_Bound(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            if(ddl.SelectedIndex == 0){
                ddl.SelectedIndex = 1;
            }

        }

        protected void SelELEC_CARBON_PRICE_OPTION_Binding(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            if (ddl.SelectedIndex == 0)
            {
                ddl.SelectedIndex = 1;
            }

        }


        public void GridView1_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            // then recall the method that bind myGvw
            GridView1.DataBind();
            
        }

        //DetailsView1_ItemInserted

        public void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            // Refresh the DataList control after a new record is inserted 
            // in the DetailsView control.
            DetailsView1.ChangeMode(DetailsViewMode.Edit);
            GridView1.DataBind();
            //Session["USERID"] = ((Label)DetailsView1.FindControl("lbluserID")).Text ;
            lblupdate.Text = "Insert Successfully at " + DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt");

            //GridView1.SelectedIndex = Int32.Parse(((Label)DetailsView1.FindControl("lbluserID")).Text);


            MultiView1.ActiveViewIndex = 0;
            MultiView2.ActiveViewIndex = 0;

            ////////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)){file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": insert detailview1");}  

            //DetailsView1.DataBind();
            //DetailsView2.DataBind();
            //DetailsView3.DataBind();

        }


        public void DetailsView1_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {

            GridView1.DataBind();
            //DetailsView2.UpdateItem(false);
            //DetailsView3.UpdateItem(false);

            ////////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)){ file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": update detailview1");}  

        }

        public void DetailsView2_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            ////////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)){ file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": update detailview2");}  
            
        }


        public void DetailsView3_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            ////////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)){file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": update detailview3");}  

        }


        private string UserCap(string username)
        {
            string str1 = username.Substring(0, 1);

            string str2 = username.Substring(1, username.Length - 1);
            return str1.ToUpper() + str2;
        }


        protected void insertRecord(string table, string UserID)
        {
            string insertcommand = "insert into " + table + " (UserID) values(" + UserID + ");";
            string connectionString = null;
            System.Configuration.ConnectionStringSettings connString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"];
            if (null != connString)
                connectionString = connString.ConnectionString;

            System.Data.SqlClient.SqlConnection connection = null;
            connection = new System.Data.SqlClient.SqlConnection(connectionString);
            connection.Open();
            System.Data.SqlClient.SqlCommand command;
            command = connection.CreateCommand();
            command.CommandText = insertcommand;
            command.ExecuteNonQuery();
            connection.Close();
        }

        protected void AddElecSite_OnClick(object sender, EventArgs e){
            insertRecord("tblCI_ELEC_SITE_DETAIL", ((Label)DetailsView1.FindControl("lbluserID")).Text);
            ((GridView)DetailsView2.FindControl("GridView2")).DataBind();
        }

        protected void AddGasSite_OnClick(object sender, EventArgs e)
        {
            insertRecord("tblCI_GAS_SITE_DETAIL", ((Label)DetailsView1.FindControl("lbluserID")).Text);
            ((GridView)DetailsView3.FindControl("GridView3")).DataBind();
        }

        protected void AddElecRPF_OnClick(object sender, EventArgs e)
        {
            insertRecord("tblCI_ELEC_RFP_DETAIL", ((Label)DetailsView1.FindControl("lbluserID")).Text);
            ((GridView)DetailsView2.FindControl("GridView4")).DataBind();
        }

        protected void AddGasRPF_OnClick(object sender, EventArgs e)
        {
            insertRecord("tblCI_GAS_RFP_DETAIL", ((Label)DetailsView1.FindControl("lbluserID")).Text);
            ((GridView)DetailsView3.FindControl("GridView5")).DataBind();
        }



        protected void GasCAF_OnClick(object sender, EventArgs e)
        {

        }

        public static System.Data.DataTable GetDataTable(SqlCommand cmd)
        {
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            System.Data.DataTable dtGet = new System.Data.DataTable();
            da.Fill(dtGet);
            return dtGet;
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsView1.ChangeMode(DetailsViewMode.Edit);
            String GridIndex = GridView1.SelectedDataKey.Value.ToString();
            ////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)) { file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": select " + GridIndex); }  


            //session
            //Session["USERID"] = GridIndex;
            tbid.Text = GridIndex;
            String ProviderCommand = "SELECT FUEL_TYPE as FUEL_TYPE FROM tblCI where USERID='" + GridIndex + "';";
            String TypeResult = "";
            string connectionString = null;
            System.Configuration.ConnectionStringSettings connString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"];
            if (null != connString)
                connectionString = connString.ConnectionString;
            System.Data.SqlClient.SqlConnection connection = null;
            try
            {
                connection = new System.Data.SqlClient.SqlConnection(connectionString);
                connection.Open();
                System.Data.SqlClient.SqlCommand command;
                System.Data.SqlClient.SqlDataReader reader;
                command = connection.CreateCommand();
                command.CommandText = ProviderCommand;
                reader = command.ExecuteReader();
                reader.Read();
                TypeResult = Convert.ToString(reader["FUEL_TYPE"]);
                reader.Close();
                connection.Close();
            }
            catch (Exception)
            {
                if (connection != null)
                {
                    connection.Dispose();
                }
            }


            tbtp.Text = TypeResult;

            if (tbtp.Text == "")
            {
                MultiView1.ActiveViewIndex = 0;
                MultiView2.ActiveViewIndex = 0;
            }
            else if (tbtp.Text == "Electricity")
            {

                MultiView1.ActiveViewIndex = 1;
                MultiView2.ActiveViewIndex = 0;

            }
            else if (tbtp.Text == "Gas")
            {

                MultiView1.ActiveViewIndex = 0;
                MultiView2.ActiveViewIndex = 1;

            }
            else if (tbtp.Text == "Dual")
            {

                MultiView1.ActiveViewIndex = 1;
                MultiView2.ActiveViewIndex = 1;

            }


        }

        protected void selFUEL_TYPE_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (((RadioButtonList)DetailsView1.FindControl("selFUEL_TYPE")).SelectedValue == "")
            {
                MultiView1.ActiveViewIndex = 0;
                MultiView2.ActiveViewIndex = 0;
            }
            else if (((RadioButtonList)DetailsView1.FindControl("selFUEL_TYPE")).SelectedValue == "Electricity")
            {

                MultiView1.ActiveViewIndex = 1;
                MultiView2.ActiveViewIndex = 0;

            }
            else if (((RadioButtonList)DetailsView1.FindControl("selFUEL_TYPE")).SelectedValue == "Gas")
            {
                MultiView2.ActiveViewIndex = 1;
                MultiView1.ActiveViewIndex = 0;

            }
            else if (((RadioButtonList)DetailsView1.FindControl("selFUEL_TYPE")).SelectedValue == "Dual")
            {

                MultiView1.ActiveViewIndex = 1;
                MultiView2.ActiveViewIndex = 1;

            }
        }

        protected void btnAddG1_click(object sender, EventArgs e)
        {
            DetailsView1.ChangeMode(DetailsViewMode.Insert);
            MultiView1.ActiveViewIndex = 0;
            MultiView2.ActiveViewIndex = 0;
            
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {

            DetailsView1.UpdateItem(false);
            DetailsView2.UpdateItem(false);
            DetailsView3.UpdateItem(false);
        }

        protected void btnsearch_Click(object sender, EventArgs e)
        {
            
            //GridView1.DataBind();
            //gridViewTotalRowCount.Text = Convert.ToString(this.GridView1.Rows.Count * this.GridView1.PageCount);
            //gridViewTotalRowCount.Text = Convert.ToString(GridView1.Rows.Count);
            //DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
            //int numberOfRows = int.Parse(dv.Table.Compute("Count(USERID)", "").ToString());
            //string rowFilter = SqlDataSource1.FilterExpression;
            //int rowcount = dv.Count;
            //int numberOfRows = int.Parse(dv.Table.Compute("Count(USERID)", rowFilter).ToString());
            //gridViewTotalRowCount.Text = Convert.ToString(rowcount);

            ////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)) { file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": search " + ((TextBox)FindControl("searchBox")).Text); }  


        }

        public void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            //gridViewTotalRowCount.Text = Convert.ToString(e.AffectedRows);

        }

        public void SqlDataSource2_Updated(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (e.AffectedRows>0)
            {
                lblupdate.Text = "Last Successful Update at " + DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt");

            }

        }

        public void SqlDataSource1_Deleted(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (e.AffectedRows > 0)
            {
                lblupdate.Text = "Delete Successfully at " + DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt");
                ////using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("\\gol.txt"), true)) { file.WriteLine(DateTime.Now.ToString(@"dd\/MM\/yyyy h\:mm:ss tt") +"  "+ (String)Session["UserName"] + ": delete "); }  

            }

        }



        protected void btnexport_Click(object sender, EventArgs e)
        {
            GridView1.AllowPaging = false;
            GridView1.DataBind();
            Response.Clear();
            Response.AppendHeader("Content-Disposition", "attachment;filename= " + Server.UrlEncode("Export.xls"));
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("EN", true);
            System.IO.StringWriter stringWrite = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            GridView1.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
            GridView1.AllowPaging = true;
        }

        override public void VerifyRenderingInServerForm(System.Web.UI.Control control)
        { }

        protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}
//OPERATOR LIKE '%{0}%' or FIRST_NAME  LIKE '%{0}%' or ELEC_STAT  LIKE '%{0}%' or LAST_NAME  LIKE '%{0}%'  or COMPANY_NAME  LIKE '%{0}%'